//
//  MyHappyTimeVC.m
//  BestLearning
//
//  Created by 星道 on 17/8/17.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "MyHappyTimeVC.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <BaiduBCEBOS/BaiduBCEBOS.h>
#import <BaiduBCESTS/BaiduBCESTS.h>
#import <BaiduBCEVOD/BaiduBCEVOD.h>
#import "ReceiveFlowerView.h"

#define titleLength 30
#define desLength 200
@interface MyHappyTimeVC ()<UITextFieldDelegate,UITextViewDelegate>
{
    /** 视频预览图 */
    IBOutlet UIImageView *_VideoPlaceholder;
    /** 标题 */
    IBOutlet UITextField *_Title;
    /** 描述 */
    IBOutlet UITextView *_Des;
    /** 描述的占位 */
    IBOutlet UILabel *_DesPlaceholder;
    /** 标题限制数 */
    IBOutlet UILabel *_TitleLength;
    /** 描述限制数 */
    IBOutlet UILabel *_DesLength;
    /** QQ空间 */
    IBOutlet UIButton *_QQ;
    /** 朋友圈 */
    IBOutlet UIButton *_WeChat;
    /** 发布按钮 */
    IBOutlet UIButton *Send;
}
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;

@property (nonatomic,copy)NSString *url;
@property (nonatomic,copy)NSString *imageIcon;
@property (nonatomic,strong) VODGenerateMediaIDResponse *mediaIdResponses;
@property (nonatomic,strong) VODClient *vodClient;
@property (nonatomic,copy)NSString *mediaID;
@property (nonatomic,copy)NSString *uirlStr;
@property (nonatomic, strong) MBProgressHUD *HUD;
@property (nonatomic,copy)NSString *weChatOne;
@property (nonatomic,copy)NSString *qqChatOne;
@property (nonatomic,strong) UIButton *tempButton;
@end

@implementation MyHappyTimeVC


- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"视频上传";
    
    _VideoPlaceholder.image = [self GetVideoPreViewImage];
    Send.layer.cornerRadius = 6.0f;
    Send.layer.masksToBounds = YES;
    self.cancelBtn.layer.cornerRadius = 6.0f;
    self.cancelBtn.layer.masksToBounds = YES;

}

#pragma mark - 方法
/** 获取视频的第一帧的图片 */
- (UIImage*)GetVideoPreViewImage
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:self.VideoPath] options:nil];
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *img = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return img;
}


#pragma mark - 事件
/** 播放影音 */
- (IBAction)PlayMovie:(UIButton *)sender
{
    NSURL *URL = [NSURL fileURLWithPath:self.VideoPath];
    MPMoviePlayerViewController  * moviePlayerController = [[MPMoviePlayerViewController alloc] initWithContentURL:URL];
    [self presentMoviePlayerViewControllerAnimated:moviePlayerController];
    moviePlayerController.moviePlayer.movieSourceType=MPMovieSourceTypeFile;
}

/** 取消 */
- (IBAction)clickCancelBtn:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}


/** 发布 */
- (IBAction)Send:(UIButton *)sender
{
    // 标题是必须的，描述是可选
    // 标题、描述
 self.uirlStr = @"0";
//   [MBProgressHUD showMessage:[NSString stringWithFormat:@"%@",self.uirlStr]];

            [self HUD];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       [self mm];
   });

    
}

/** QQ */
- (IBAction)QQ:(UIButton *)sender
{
    self.tempButton.selected = !self.tempButton.selected;
    self.tempButton = sender;
    self.tempButton.selected = !self.tempButton.selected;
}

///** 朋友圈 */
//- (IBAction)WeChat:(UIButton *)sender
//{
//    sender.selected = !sender.selected;
//    
//    if (sender.selected) {
//        
//        self.weChatOne = @"301";
//        
//    }else{
//        self.weChatOne = @"302";
//        
//    }
//    
//    
//   }

- (void)textViewDidChange:(UITextView *)textView
{
    _DesPlaceholder.hidden = textView.text.length;
}



#pragma mark - getter

- (void)mm{
    //STS方式获得鉴权credentials对象，推荐采用
    //    BCESTSCredentials* credentials = [BCESTSCredentials new];
    //
    //
    //    NSString *accessKeys =  [self MD5Sring:@"a6cc850f1475400f9af23ec2f2bbf3a0"];
    //    NSString *secretKeys  = [self MD5Sring:@"56b4592ac55244e3bc4da0e67a133f15"];
    //    NSString *sessionTokens  = [self MD5Sring:@"bdc82de217304595"];
    //
    //
    //
    //    credentials.accessKey = accessKeys;
    //    credentials.secretKey = secretKeys;
    //    credentials.sessionToken = sessionTokens ;
    
    //或者AKSK方式鉴权credentials对象，两种方式任选其一即可
    BCECredentials* credentials = [BCECredentials new];
    credentials.accessKey = @"a6cc850f1475400f9af23ec2f2bbf3a0";
    credentials.secretKey = @"56b4592ac55244e3bc4da0e67a133f15";
    
    
    //初始化鉴权后的BOSClient对象
    BOSClientConfiguration* bosConfig = [BOSClientConfiguration new];
    bosConfig.credentials = credentials;
    BOSClient *bosClient = [[BOSClient alloc] initWithConfiguration:bosConfig];
    
    //初始化鉴权后的VODClient对象
    VODClientConfiguration* vodConfig = [VODClientConfiguration new];
    vodConfig.credentials = credentials;
    VODClient *vodClient = [[VODClient alloc] initWithConfiguration:vodConfig];
    
    [self mmm:vodClient bOSClient:bosClient];
}

- (void)mmm:(VODClient *)vodClient bOSClient:(BOSClient *)bosClient{
    
    VODGenerateMediaIDRequest* request = [[VODGenerateMediaIDRequest alloc] init];
    
    
    // request.mode = @"<mode>";
    BCETask *task = [vodClient generateMediaID:request];//此处的vodClient指向之前的步骤中已经鉴权并初始化的VodClient对象
    __block NSString* mediaID;
    __block VODGenerateMediaIDResponse *res;
    task.then(^(BCEOutput* output) {
        if (output.response) {
            //任务执行成功，通过返回的response获取mediaId等相关字段
            res = (VODGenerateMediaIDResponse*)output.response;
            mediaID = res.mediaID;
            NSString* sourceBucket = res.sourceBucket;
            NSString* sourceKey = res.sourceKey;
            self.mediaIdResponses = res;
            self.mediaID = mediaID;
            self.vodClient = vodClient;
            
            
            NSLog(@"ddddddddd%@  %@   %@",mediaID,sourceBucket,sourceKey);
            [self mmmmbOSClient:bosClient mediaIdResponse:res vodClient:vodClient mediaID:mediaID];
            
            //执行任务成功相关逻辑代码
        }
        
        if (output.error) {
            //执行任务失败相关逻辑代码
            NSLog(@"eeeeeeeeeeeeeeeeeeeeddddddddd%@",output.error);
        }
    });
    [task waitUtilFinished];
    
    
}

- (void)mmmmbOSClient:(BOSClient *)bosClient mediaIdResponse:(VODGenerateMediaIDResponse *)mediaIdResponses vodClient:(VODClient *)vodClient mediaID:(NSString *)mediaID{
    
    NSString *uploadFile = self.VideoPath;
    
    BOSObjectContent* content = [[BOSObjectContent alloc] init];
    content.objectData.file = uploadFile;
    
    VODGenerateMediaIDResponse *mediaIdResponse = mediaIdResponses;//此处mediaIdResponse指向步骤2中请求到的媒资数据
    
    BOSPutObjectRequest* request = [[BOSPutObjectRequest alloc] init];
    request.bucket = mediaIdResponse.sourceBucket;
    request.key = mediaIdResponse.sourceKey;
    request.objectContent = content;
    
    
    
    BCETask* task = [bosClient putObject:request];//此处的bosClient指向之前的步骤中已经鉴权并初始化的VodClient对象
    task.then(^(BCEOutput* output) {
        
        if (output.progress) {//上传中
            //处理相关逻辑
            //可以通过 output.progress.floatValue 获取当前上传进度


            dispatch_async(dispatch_get_main_queue(), ^{

            if (100 == [output.progress  integerValue]) {
                    self.HUD.label.text = @"正在上传...99%";
            }else{
              
                self.HUD.label.text = [NSString stringWithFormat:@"正在上传...%ld%@",[output.progress integerValue],@"%"];

            }
            });



        }
        
        if (output.response) {//上传成功
            //处理相关逻辑
            
            
            NSLog(@"%@dddddde",output.response);
            
            [self mmmmmmediaIdResponse:mediaIdResponses vodClient:vodClient mediaID:mediaID];
            
        }
        
        if (output.error) {//上传
            NSLog(@"%@",output.error);
            //处理相关逻辑
               [self mmmmmmediaIdResponse:mediaIdResponses vodClient:vodClient mediaID:mediaID];
        }
        
    });
    [task waitUtilFinished];
    
    
    
    
}

- (void)mmmmmmediaIdResponse:(VODGenerateMediaIDResponse *)mediaIdResponses  vodClient:(VODClient *)vodClient mediaID:(NSString *)mediaID{
    
    VODProcessMediaRequest* request = [VODProcessMediaRequest new];
    //VODGenerateMediaIDResponse* mediaIdResponse = mediaIdResponses;//此处mediaIdResponse指向步骤2中请求到的媒资数据
    request.mediaId = mediaID;
//    request.attributes.mediaTitle = _Title.text;
    request.attributes.mediaTitle = @"三好评价视频";
    request.attributes.mediaDescription = _Des.text?:@"";
    request.sourceExtension = @"mp4";
    request.transcodingPresetGroupName = @"vod.inbuilt.mp4";
    
    
    
    BCETask *task = [vodClient processMedia:request];
    task.then(^(BCEOutput* output) {
        if (output.response) {//处理媒资请求成功
            //处理相关业务逻辑
            
            NSLog(@"%@",output.response);
            
            
            [self mmmmmmmmmmm:mediaIdResponses vodClient:vodClient mediaID:mediaID];
            
            
            
        }
        
        if (output.error) {//处理媒资请求错误
            //处理相关业务逻辑
            NSLog(@"%@",output.error);
            //Error Domain=bucket name is invalid Code=-1 "(null)"
        }
    });
    [task waitUtilFinished];
    
    
}



- (void)mmmmmmmmmmm:(VODGenerateMediaIDResponse *)mediaIdResponses  vodClient:(VODClient *)vodClient mediaID:mediaID{
    
    __block VODGetMediaResponse* response = nil;
    //VODGenerateMediaIDResponse* mediaIdResponse = mediaIdResponses;//此处mediaIdResponse指向步骤2中请求到的媒资数据
    BCETask *task = [vodClient getMedia:mediaID];
    NSLog(@"%@",mediaID);
    task.then(^(BCEOutput* output) {
        
        if (output.response) {//处理媒资请求成功
            //通过返回的response获取mediaId等相关字段
            response = (VODGetMediaResponse*)output.response;
            
            for (VODPlayableURL *url  in response.playableUrlList) {
                
                
                if ([url.transcodingPresetName isEqualToString:@"mp4_1080p"]) {
                    
                    NSLog(@"ddddddddddddddd%@",url.url);
                    
                    self.url = url.url;
                }
                
                
            }
            
            for (NSString *str  in response.thumbnailList) {
                
                NSLog(@"mmmmmmmmmmmmmmmmm%@",str);
                self.imageIcon = str;
                
                
            }

            NSLog(@"123123123123123123123123123123123");
            if (self.url.length == 0 ) {
                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self mmmmmmediaIdResponse:self.mediaIdResponses vodClient:self.vodClient mediaID:self.mediaID];
                    [self mmmmmmmmmmm:self.mediaIdResponses vodClient:self.vodClient mediaID:self.mediaID];
                });

            }else{
                
                
                NSLog(@"%@ %@",self.url,self.imageIcon);


                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self videoUrl:self.url videoIamge:self.imageIcon];
                    });

            }
            
            
            
         
            
            
            //处理相关业务逻辑
        }
        
        if (output.error) {//处理媒资请求错误
            //处理相关业务逻辑
            NSLog(@"%@",output.error);
        }
    });
    [task waitUtilFinished];
    
    
    
    
}



- (void)videoUrl:(NSString *)urls videoIamge:(NSString *)images{
    
    NSString *titleStr = @"2daa";
    _Des.text = @"daa2";
    NSString *url = [NSString stringWithFormat:@"growthTime.do?action=saveGrowthTimeVideo&img=%@&url=%@&title=%@&videoDesc=%@",images,urls,titleStr,_Des.text?:@""];
    NSLog(@"%@",url);
    
    
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//
//    [params setValue:@"saveGrowthTimeVideo" forKey:@"action"];
//    [params setValue:urls forKey:@"url"];
//    [params setValue:images forKey:@"img"];
//    [params setValue:_Title.text forKey:@"title"];
//    [params setValue:_Des.text forKey:@"videoDesc"];
//
//
//    NSLog(@"%@",params);



    
    
    [NetManager Post:LLBaseURLs(url) Auth:YES Params:nil Success:^(id Obj) {
        self.HUD.label.text = @"视频上传成功!";
        NSLog(@"%@",Obj);
        
        
        if (self.urlBlock) {
            self.urlBlock(self.url,images);
        
           
        }
        
        [self.navigationController popViewControllerAnimated:YES];

    } Fail:^(NSError *Error) {
        NSLog(@"最后出错:%@",Error);
    }];
    

    
    
   
}



-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    
    return YES;
}





- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    
}

- (MBProgressHUD *)HUD
{
    if (!_HUD)
    {
        _HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        _HUD.mode = MBProgressHUDModeText;
        _HUD.removeFromSuperViewOnHide = YES;
        _HUD.backgroundColor = ColorRGBA(0, 0, 0, 0.5);
        _HUD.bezelView.color =[[UIColor blackColor] colorWithAlphaComponent:0.5];
        _HUD.contentColor = [UIColor whiteColor];
        _HUD.label.text = @"正在上传中...0%";
    }
    return _HUD;
}
@end
